//==================================================================
//  Copyright (C) 2006-2007  Davide Pasca
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//==================================================================
/// @file
///
///
/// 
/// @author Davide Pasca
/// 
//==================================================================

#include "stdafx.h"
#include "rend_device.h"
#include "rend_index_buffer.h"

//==================================================================
///
//==================================================================
RendIndexBuffer::RendIndexBuffer( RendDevice *rdevicep, int max_indices ) :
_rdevicep(rdevicep),
_max_indices(0),
_total_alloc_size(0)
{
	ReallocBuffer( max_indices );
}

//==================================================================
void RendIndexBuffer::ReallocBuffer( int max_indices )
{
	// these are updated every time anyway (upload needs to know the actual number)
	_max_indices = max_indices;

	// if the buffer is smaller, there is no need to allocate a new one !
	if ( max_indices * sizeof(u_short) <= _total_alloc_size )
		return;

	_total_alloc_size = (_max_indices+1) * sizeof(u_short);

#ifdef TARGET_D3D
	// release the current one
	if ( _d3d_ibuffp )
	{
		_d3d_ibuffp->Release();
		_d3d_ibuffp = NULL;
	}

	D3DDevice	*d3ddevp = _rdevicep->GetD3DDevice();

	HRESULT	hr;
	hr = d3ddevp->CreateIndexBuffer( _total_alloc_size, 0, D3DFMT_INDEX16,
		0, &_d3d_ibuffp, NULL );

	if ERR_ERROR( hr )
	{
		_total_alloc_size = 0;
		throw "CreateIndexBuffer failed !";
	}
#endif
}

//==================================================================
void RendIndexBuffer::UploadData( const u_short *src_datap, int from_index, int n_indices )
{
	if ( n_indices <= 0 )
		return;

	u_int	tot_use_size = n_indices * sizeof(u_short);

#ifdef TARGET_D3D
	void	*destp;
	_d3d_ibuffp->Lock( from_index * sizeof(u_short), tot_use_size, (VOID**)&destp, NULL );
	memcpy( destp, src_datap, tot_use_size );
	_d3d_ibuffp->Unlock();
#endif
}
